package view
{
	import control.ItemFactory;
	
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.URLRequest;
	
	import model.ItemInfo;
	import model.ItemPage;

	public class Container extends Sprite
	{
		private var cellList:Array;
		private var itemList:Array;
		private var page:Array;
		private var itemPage:ItemPage;
		private var count:int=34;
		private var fromCell:Cell;
		private var toCell:Cell;
		
			//用来加载背景图片
		private var loader:Loader=new Loader();
		
		public function Container()
		{
			init();
			loadItem();
		}
		
		public function loadItem():void{
			itemList=ItemFactory.getItemList(count);
			itemPage=new ItemPage(itemList);
			page=itemPage.getPage(1)
			//设置物品显示到包中
			for(var i:uint=0;i<itemPage.pageSize;i++){
				var itemInfo:ItemInfo=page[i] as ItemInfo;
				var cell:Cell=new Cell(itemInfo);
				
				cell.x=14+(i%6)*36;
				cell.y=51+uint(i/6)*36;
				cell.addEventListener(MouseEvent.MOUSE_DOWN,mouseDownHandler);
				cell.addEventListener(MouseEvent.MOUSE_UP,mouseUpHandler);
				this.addChild(cell);
				
			}
		}
		
		/**
		 * 初始化背包背景，拖拽动作
		 */
		private function init():void{
			var url:URLRequest=new URLRequest("bg.png");
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onloadedBackground);
			loader.load(url);
			//this.addEventListener(MouseEvent.MOUSE_DOWN,mouseDownHandler);
			//this.addEventListener(MouseEvent.MOUSE_UP,mouseUpHandler);
		}
		/**
		 * 添加背景图片
		 */
		private function onloadedBackground(e:Event):void{
			var image:Bitmap;image=Bitmap(loader.content);
			this.addChild(image);
			setChildIndex(image,0);//设置背景图片显示在最			
		}
		
		/**
		 * 鼠标点下
		 */
		private function mouseDownHandler(e:MouseEvent):void{
			fromCell=(e.currentTarget as Cell);
			var copyCell:Sprite=fromCell.getCopy();
			copyCell.x=mouseX+fromCell.width/2;
			copyCell.y=mouseY+fromCell.height/2;
			copyCell.alpha=0.5;
			this.addChild(copyCell);
			
			copyCell.startDrag();
		}
		/**
		 * 鼠标放开
		 */
		private function mouseUpHandler(e:MouseEvent):void{
			
			trace((e.currentTarget as Cell).itemInfo.imageURL);
		}
	}
}